package com.zhen.aikan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhen.aikan.entity.Danmu;
import com.zhen.aikan.mapper.DanmuMapper;
import com.zhen.aikan.service.IDanmuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhen.aikan.service.IUtilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lijiazhen
 * @since 2023-09-11
 */
@Service
public class DanmuServiceImpl extends ServiceImpl<DanmuMapper, Danmu> implements IDanmuService {
    @Autowired
    private IUtilService utilService;

    @Override
    public List<List<Object>> getDanmuByVodIdAndEpisode(String vodId, String episode) {
        if (!StringUtils.hasText(vodId) || !StringUtils.hasText(episode)) {
            return null;
        }
        QueryWrapper<Danmu> wrapper = new QueryWrapper<>();
        wrapper.eq("vod_id", vodId);
        wrapper.eq("vod_episode", episode);
        List<List<Object>> danmus = baseMapper.selectList(wrapper).stream().map(item -> {
            List<Object> list = new ArrayList<>();
            list.add(item.getTime());
            list.add(item.getType());
            list.add(item.getColor());
            list.add(item.getUserId());
            list.add(item.getContent());
            return list;
        }).collect(Collectors.toList());
        return danmus;
    }

    @Override
    public boolean saveDanmu(Map<String, String> param) {
        //判断是否登录
        Map<Object, Object> userByToken = utilService.getUserByToken(param.get("token"));
        if (userByToken == null) {
            return false;
        }
        String danmuId = param.get("id");
        String[] s = danmuId.split("_");
        Danmu danmu = new Danmu();
        danmu.setVodId(Integer.parseInt(s[0]));
        danmu.setVodEpisode(Integer.parseInt(s[1]));
        danmu.setColor(param.get("color"));
        danmu.setTime(new BigDecimal(param.get("time")));
        danmu.setType(Integer.parseInt(param.get("type")));
        danmu.setUserId(param.get("author"));
        danmu.setContent(param.get("text"));

        return save(danmu);
    }
}
